/**
 * 

 */
package edu.vt.ece.rt.quorum.messsages.types;

import org.jgroups.Message;

import edu.vt.ece.rt.quorum.ClustersManager;
import edu.vt.ece.rt.quorum.messsages.QMessage;
import edu.vt.ece.rt.quorum.util.Names;
import edu.vt.ece.rt.quorum.util.WaitObject;

/**
 * 
 * @author Sudhanshu
 * 
 */
public class BenchCompletion extends QMessage implements Runnable {

	boolean req; // specify root to cluster or cluster to root

	boolean done;	//To specify if it is request, is it for completion
	/**
	 * 
	 */
	public BenchCompletion(boolean toNodes, boolean allDone) {
		super(MessageType.BenchCompletion);
		req = toNodes;
		done = allDone;
	}

	@Override
	public void run() {
		if(req){
			if(done){//Again from root to node to ask exit
				WaitObject w = ClustersManager.waitTillDone;
				synchronized (w) {
					w.notifyAll();		//All done, exit now
				}				
			}else{
				//Incoming message coming from root, update node wait-object
				WaitObject w = ClustersManager.waitTillDone;
				w.rootAdr = getSrcAddr();
				w.rootDone.set(true);		//Reader of root done will reply to root
			}			
		}else{	//On coming back to root, should execute only on root node
			WaitObject w = ClustersManager.waitTillDone;		
			synchronized (w) {
				if(w.counter.decrementAndGet() == 0){	//If you are the last, tell everyone to exit
					try {
						//Now notify all to 
						ClustersManager.getCluster(Names.base).send(new Message(null, new BenchCompletion(true, true)));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

}
